﻿#include "mainwindow.h"

#include <QHostAddress>

#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow) {
  ui->setupUi(this);
  setWindowTitle("TCP - 服务器");
  ui->port->setText("9999");  //设置端口
  m_server = new QTcpServer(this);

  //由QTcplisten::listen 触发
  connect(m_server, &QTcpServer::newConnection, this, [=]() {
    m_tcp = m_server->nextPendingConnection();  //获得用于通信套接字
    ui->record->append("成功和客户端建立了新的连接...");
    m_status->setPixmap(
        QPixmap(":/connect.png").scaled(30, 30));  //设置连接状态图片
    //套接字 读任务 就绪
    connect(m_tcp, &QTcpSocket::readyRead, this, [=]() {
      // 接收数据
      QString recvMsg = m_tcp->readAll();  //获取缓存区所有数据
      ui->record->append("客户端Say: " + recvMsg);  //拼接到聊天框
    });
    //套接字连接断开
    connect(
        m_tcp, &QTcpSocket::disconnected, this,
        [=]()  //
        {
          ui->record->append("客户端已经断开了连接...");
          m_tcp->deleteLater();  //手动析构
          /* QTcpSocket 是 QTcpServer
           * 的子对象，可以由QTcpServer自动析构（对象树）
           */
          m_status->setPixmap(
              QPixmap(":/disconnect.png").scaled(30, 30));  //设置断开连接图标
        });
  });
  //设置初始状态栏
  m_status = new QLabel;
  m_status->setPixmap(QPixmap(":/disconnect.png").scaled(30, 30));
  ui->statusBar->addWidget(
      new QLabel("连接状态: "));  //自动将label 父对象设置为 statusBar
  ui->statusBar->addWidget(m_status);  //拼接到文字后面
}

MainWindow::~MainWindow() { delete ui; }

void MainWindow::on_startServer_clicked() {
  unsigned short port = ui->port->text().toInt();  //设置端口
  m_server->listen(QHostAddress::Any, port);  //绑定本机地址，并监听
  ui->startServer->setEnabled(false);  //开启服务后，停止按钮功能
}

void MainWindow::on_sendMsg_clicked() {
  QString sendMsg = ui->msg->toPlainText();  //读取输入框文本
  m_tcp->write(sendMsg.toUtf8());            //通过套接字发送
  ui->record->append("服务器Say: " + sendMsg);  //发送的信息 拼接到聊天框
  ui->msg->clear();                             //清空输入框
}
